package user

import (
	"github.com/gin-gonic/gin"
	. "myplatform/handler"
	"myplatform/libs/auth"
	"myplatform/libs/errcode"
	"myplatform/libs/token"
	"myplatform/model"
)

func RegisterHTML(c *gin.Context) {
	c.HTML(200, "register.html", gin.H{})
}

func Register(c *gin.Context) {
	var u model.UserModel
	if err := c.ShouldBind(&u); err != nil {
		SendRsp(c, errcode.ParamBindError, nil)
		return
	}
	//加密密码
	if err := u.Encrypt(); err != nil {
		SendRsp(c, errcode.AuthFailError, nil)
		return
	}
	//判断用户是否存在,存在输出
	if err := model.Justify(u.PhoneNumber); err == nil {
		SendRsp(c, errcode.UserRegisterFail, nil)
	} else {
		if err := u.Create(); err != nil {
			SendRsp(c, errcode.DataBaseError, nil)
			return
		}
		//注册成功跳转到登录页面
		c.Redirect(301, "/login")
	}

}

func LoginHTML(c *gin.Context) {
	c.HTML(200, "login.html", gin.H{})
}

// 接收登录信息的结构体
type UserLogin struct {
	PhoneNumber string `json:"phonenumber" form:"phonenumber" binding:"required"`
	Password    string `json:"password" form:"password" binding:"required"`
}

// 登录验证
func Login(c *gin.Context) {
	var userlogin UserLogin
	if err := c.ShouldBindJSON(&userlogin); err != nil {
		SendRsp(c, errcode.ParamBindError, nil)
		return
	}
	//根据Phonenumber得到用户信息
	u, err := model.GetUserByPhonenumber(userlogin.PhoneNumber)
	if err != nil {
		SendRsp(c, errcode.NoSuchUser, nil)
		return
	}
	//比较密码是否正确
	if err := auth.Compare(u.Password, userlogin.Password); err != nil {
		SendRsp(c, errcode.PasswordAuthFail, nil)
		return
	}
	//生成token
	if t, err := token.Sign(token.TokenContext{Uid: u.Uid, PhoneNumber: u.PhoneNumber}, ""); err != nil {
		SendRsp(c, errcode.TokenGenerateError, nil)
		return
	} else {
		//SendRsp(c, errcode.OK, t)
		SendRsp(c, errcode.OK, gin.H{"token": t})
	}
}

// GetUserProfile 显示用户的个人信息页面
func GetUserProfile(c *gin.Context) {
	// 从 gin.Context 中获取解析后的 token 上下文
	ctx, exists := c.Get("user")
	if !exists {
		SendRsp(c, errcode.ErrcodeInternalError, gin.H{"error": "user context not found"})
		return
	}

	userCtx := ctx.(*token.TokenContext)

	// 根据 UID 获取用户信息
	u, err := model.GetUserInfoByUid(userCtx.Uid)
	if err != nil {
		SendRsp(c, errcode.ErrcodeInternalError, gin.H{"error": "Failed to get user information"})
		return
	}

	// 返回用户信息
	SendRsp(c, errcode.OK, u)

}

func GetUserProfileHTML(c *gin.Context) {
	c.HTML(200, "userinfo.html", gin.H{})
}

// 根据uid找帖子
func GetPostByuid(c *gin.Context) {
	// 从 gin.Context 中获取解析后的 token 上下文
	ctx, exists := c.Get("user")
	if !exists {
		SendRsp(c, errcode.ErrcodeInternalError, gin.H{"error": "user context not found"})
		return
	}
	userCtx := ctx.(*token.TokenContext)
	// 根据 UID 获取post
	p, err := model.GetPostByUid(userCtx.Uid)
	if err != nil {
		SendRsp(c, errcode.ErrcodeInternalError, gin.H{"error": "Failed to get post information"})
		return
	}
	// 返回用户信息
	SendRsp(c, errcode.OK, p)
}

func GetPostByuidHTML(c *gin.Context) {
	c.HTML(200, "mypost.html", gin.H{})
}
